package com.studerb.view.newsGroups;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.model.NewsGroup;

public class NewsGroupsTable extends JTable {
    Logger logger = Logger.getLogger(NewsGroupsTable.class);
    @Autowired private NewsGroupsTableModel newsGroupsTableModel;
    @Autowired private NewsGroupDetailsPane newsGroupDetailsPane;
    
    public void init() {
        setModel(newsGroupsTableModel);
        setAutoCreateRowSorter(true);
        setFillsViewportHeight(true);
        setToolTipText(null);
        this.selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.selectionModel.addListSelectionListener(new NewsGroupsTableSL());
    }
    
    class NewsGroupsTableSL implements ListSelectionListener {

        @Override public void valueChanged(ListSelectionEvent e) {
            if(e.getValueIsAdjusting()){
                return;
            }

            int selectedRowIndex  = getSelectedRow();
            if(selectedRowIndex != -1){
                int convertedIndex = convertRowIndexToModel(selectedRowIndex);
                NewsGroup newsGroup = newsGroupsTableModel.getNewsGroup(convertedIndex);
                newsGroupDetailsPane.setSelectedNewsGroup(newsGroup);
            }
        }
    }
}
